<template>
  <div class="simple-chart-container">
    <div class="debug-info">
      <div>容器状态: {{ chartRef ? '✅ 已渲染' : '❌ 未渲染' }}</div>
    </div>
    <div 
      ref="chartRef" 
      class="chart"
      style="width: 100%; height: 400px; border: 1px solid #ccc; background: #fff;"
    ></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';

// 响应式引用
const chartRef = ref(null);
let chartInstance = null;
let resizeHandler = null;

// 生成模拟数据
const generateMockData = () => {
  const data = [];
  const now = new Date();
  
  for (let i = 11; i >= 0; i--) {
    const month = now.getMonth() - i + 1;
    data.push({
      month: `${month}月`,
      count: 100 + Math.floor(Math.random() * 200)
    });
  }
  
  return data;
};

// 初始化图表
const initChart = () => {
  console.log('初始化简单图表');
  if (!chartRef.value) return;
  
  // 清理旧实例
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartRef.value);
  
  // 准备数据
  const mockData = generateMockData();
  const months = mockData.map(item => item.month);
  const counts = mockData.map(item => item.count);
  
  // 基本配置
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => `${params[0].axisValue}: ${params[0].value}人`
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: counts,
      type: 'line'
    }]
  };
  
  // 设置配置
  chartInstance.setOption(option);
  
  // 窗口大小变化处理
  resizeHandler = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };
  
  window.addEventListener('resize', resizeHandler);
};

// 组件挂载时初始化
onMounted(() => {
  console.log('SimpleChart 组件挂载');
  // 延迟一点时间确保DOM已渲染
  setTimeout(() => {
    initChart();
  }, 100);
});

// 组件卸载时清理
onUnmounted(() => {
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler);
  }
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>

<style scoped>
.simple-chart-container {
  width: 100%;
}

.debug-info {
  margin-bottom: 10px;
  font-size: 12px;
  color: #666;
}
</style>